package com.kongwg.exer;

import org.junit.Test;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author kongwg
 * @create 2020-12-18 18:11
 */
public class MyWordCount {
    @Test
    public void CountTest() {

        FileReader fr = null;
        HashMap<Character, Integer> map = null;
        BufferedReader br = null;
        try {
            map = new HashMap<>();

            fr = new FileReader("dbcp.txt");

            br = new BufferedReader(fr);

            int c;
            while ((c = br.read()) != -1) {
                char ch = (char) c;

                if (map.get(ch) == null) {
                    map.put(ch, 1);

                } else {
                    map.put(ch, map.get(ch) + 1);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {

                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        //写数据
        BufferedWriter bw = null;
        try {
            FileWriter fw = new FileWriter("mywordcount.txt");
            bw = new BufferedWriter(fw);

            Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();

            Iterator<Map.Entry<Character, Integer>> iterator = entrySet.iterator();

            while (iterator.hasNext()) {
                Map.Entry<Character, Integer> entry = iterator.next();
                switch (entry.getKey()) {
                    case ' ':
                        bw.write("空格=" + entry.getValue());
                        break;
                    case '\n':
                        bw.write("换行=" + entry.getValue());
                        break;
                    case '\t':
                        bw.write("tab建=" + entry.getValue());
                        break;
                    case '\r':
                       bw.write("回车=" + entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey() + "=" + entry.getValue());
                }
                bw.newLine();


            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {

                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
